﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using NetCoreCMS.Common;
using NetCoreCMS.IServices;
using NetCoreCMS.Models;
using NetCoreCMS.ShopCart;

namespace NetCoreCMS.Web.Areas.Web.Controllers
{
    public class ShoppingController : BaseController
    {
        public string goodsJsonValue = string.Empty;
        public Users userModel;
        public List<cart_items> goodsList = new List<cart_items>();
        public cart_total goodsTotal = new cart_total();
        public Orderconfig orderConfig;
        public IUser_addr_bookService _user_addr_book { get; set; }
        public IPaymentService _payment { get; set; }
        public IExpressService _express { get; set; }
        public IArticleService _article { get; set; }
        public IArticle_goodsService _article_goods { get; set; }
        public IUser_groupsService _user_groups { get; set; }
        public IActionResult Index()
        {
            orderConfig=Common.XMLConfig.Orderconfig.loadConfig(_env.ContentRootPath);
            goodsJsonValue = Request.Cookies[CMSKeys.COOKIE_SHOPPING_BUY]; //获取商品JSON数据
            int group_id = 0; //会员组ID
            userModel = GetUserInfo(); //获取会员信息
            if (userModel == null)
            {
                //如果不支持匿名购物则跳转到登录页面
                if (orderConfig.anonymous == 0)
                {
                    return Redirect("/Web/Login/Index"); //自动跳转URL
                }
            }
            else
            {
                group_id = userModel.group_id;
            }
            //获取商品列表
            if (string.IsNullOrEmpty(goodsJsonValue))
            {
                return ToError("对不起，无法获取您要购买的商品！");
            }
            try
            {
                List<cart_keys> ls = (List<cart_keys>)JsonHelper.JSONToObject<List<cart_keys>>(goodsJsonValue);
                ShopCartHelper shopcart = new ShopCartHelper(_article, _user_groups, _article_goods,HttpContext);
                goodsList = shopcart.ToList(ls, group_id); //商品列表
                goodsTotal = shopcart.GetTotal(goodsList); //商品统计
            }
            catch
            {
                return ToError("对不起，商品的传输参数有误！");
            }
            ViewBag.userModel = userModel;
            ViewBag.goodsList = goodsList;
            ViewBag.goodsTotal = goodsTotal;
            ViewBag.orderConfig = orderConfig;
            ViewBag.addrList = _user_addr_book.GetList("where user_id=" + userModel.id);
            ViewBag.paymentList =_payment.GetList("where is_lock=0");
            ViewBag.expressList =_express.GetList();
            return View();
        }
    }
}